const URL = require('url');
const querystring = require('querystring');

let url = 'http://www.baidu.com:80/ppp/%E4%B8%8A%E6%B5%B7.html?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7';
let urlObj = URL.parse(url);
/*
Url {
  protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.baidu.com:80',
  port: '80',
  hostname: 'www.baidu.com',
  hash: null,

  search: '?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7',
  query: 'name=mike&age=10&city=%E4%B8%8A%E6%B5%B7',
  pathname: '/ppp/%E4%B8%8A%E6%B5%B7.html',
  path: '/ppp/%E4%B8%8A%E6%B5%B7.html?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7',
  href: 'http://www.baidu.com:80/ppp/%E4%B8%8A%E6%B5%B7.html?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7' }
*/
console.log(urlObj);
console.log(decodeURIComponent(urlObj.pathname), decodeURIComponent(urlObj.query));
console.log(querystring.parse(urlObj.query), querystring.parse(decodeURIComponent(urlObj.query)));
console.log("------------------------");

let url2 = '/ppp/%E4%B8%8A%E6%B5%B7.html?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7';
let urlObj2 = URL.parse(url2, true);
/*
Url {
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,

  search: '?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7',
  query: { name: 'mike', age: '10', city: '上海' },
  pathname: '/ppp/%E4%B8%8A%E6%B5%B7.html',
  path: '/ppp/%E4%B8%8A%E6%B5%B7.html?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7',
  href: '/ppp/%E4%B8%8A%E6%B5%B7.html?name=mike&age=10&city=%E4%B8%8A%E6%B5%B7' }
*/
console.log(urlObj2);
console.log(decodeURIComponent(urlObj2.pathname));
console.log("------------------------");

// encodeURI()主要用于整个URI(例如，http://www.jxbh.cn/illegal value.htm)，而encode-URIComponent()主要用于对URI中的某一段(例如前面URI中的illegal value．htm)进行编码。
// 它们的主要区别在于，encodeURI()不会对本身属于URI的特殊字符进行编码，例如冒号、正斜杠、问号和井字号；而encodeURIComponent()则会对它发现的任何非标准字符进行编码。来看下面的例子：
var uri="http://www.jxbh.cn/汉字/illegal value.htm#start";
console.log(encodeURI(uri));// http://www.jxbh.cn/%E6%B1%89%E5%AD%97/illegal%20value.htm#start
console.log(encodeURIComponent(uri));// http%3A%2F%2Fwww.jxbh.cn%2F%E6%B1%89%E5%AD%97%2Fillegal%20value.htm%23start

var enuri = "http://www.jxbh.cn/%E6%B1%89%E5%AD%97/illegal%20value.htm#start";
console.log(decodeURI(enuri));// http://www.jxbh.cn/汉字/illegal value.htm#start
console.log(decodeURIComponent(enuri));// http://www.jxbh.cn/汉字/illegal value.htm#start

var enuri2 = "http%3A%2F%2Fwww.jxbh.cn%2F%E6%B1%89%E5%AD%97%2Fillegal%20value.htm%23start"
console.log(decodeURI(enuri2));// http%3A%2F%2Fwww.jxbh.cn%2F汉字%2Fillegal value.htm%23start
console.log(decodeURIComponent(enuri2));// http://www.jxbh.cn/汉字/illegal value.htm#start